package com.ym;

/** 
 * @ClassName: AESUtil 
 * @Author cym
 * @Date 2015年2月12日 下午4:24:59 
 * @Modify  
 * @CopyRight 珍诚医药在线股份有限公司 
 */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 加密
 */
public class AESUtil {
	// 16位秘钥
	private static final String CRYPT_KEY = "杭州珍诚网络科技有限公司AES码";
	private static final String AES = "AES";
	private static final String ENCODING = "ASCII";

	/**
	 * 解密方法
	 */
	public static String decrypt(String src) throws Exception {
		try {
			byte[] raw = CRYPT_KEY.getBytes(ENCODING);
			SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
			Cipher cipher = Cipher.getInstance(AES);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] encrypted = hex2byte(src);
			byte[] original = cipher.doFinal(encrypted);
			String originalString = new String(original);
			return originalString;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 加密方法
	 */
	public static String encrypt(String src) throws Exception {
		byte[] raw = CRYPT_KEY.getBytes(ENCODING);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);

		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

		byte[] encrypted = cipher.doFinal(src.getBytes());
		return byte2hex(encrypted).toLowerCase();
	}

	private static byte[] hex2byte(String hex) {
		if (hex == null)
			return null;
		int l = hex.length();
		if (l % 2 == 1)
			return null;
		byte[] bytes = new byte[l / 2];
		for (int i = 0; i != l / 2; i++)
			bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2),
					16);
		return bytes;
	}

	private static String byte2hex(byte[] bytes) {
		String hs = "";
		String stmp = "";
		for (int i = 0; i < bytes.length; i++) {
			stmp = (java.lang.Integer.toHexString(bytes[i] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	public static void main(String[] args) throws Exception {
		String ID = "等待加密的内容发送到发送到发送到非进口量交罚款拉伸到进来看进口量放假啊SD卡来减肥";
		String idEncrypt = encrypt(ID);
		System.out.println(idEncrypt);
		String idDecrypt = decrypt(idEncrypt);
		System.out.println(idDecrypt);
	}
}
